/*
*  自定义表单验证器
*  1.电话号码
*  2.邮箱地址
*/

import {provide, Directive, forwardRef} from 'angular2/core';
import {isBlank, isString, CONST_EXPR} from 'angular2/src/facade/lang';
import {Control, NG_VALIDATORS} from 'angular2/common'

const TELPHONE_VALIDATOR =
    CONST_EXPR(provide(NG_VALIDATORS, {useExisting: forwardRef(() => TelphoneValidator), multi: true}));
    
/**
 * A Directive that adds the `tel` validator to any controls marked with the
 * `tel` attribute, via the {@link NG_VALIDATORS} binding.
 *
 * ### Example
 *
 * ```
 * <input ngControl="fullName" telphone>
 * ```
 */
@Directive({
  selector: '[type=tel][ngControl],[type=tel][ngFormControl],[type=tel][ngModel]',
  providers: [TELPHONE_VALIDATOR]
})
export class TelphoneValidator {
    telRegExp = /^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/; 
    
    constructor () {}
    
    validate(control: Control): {[key: string]: any} { 
        return isBlank(control.value) || !this.telRegExp.test(control.value) ?
               {"telphone": true} :
               null;
    }
}

const EMAIL_VALIDATOR =
    CONST_EXPR(provide(NG_VALIDATORS, {useExisting: forwardRef(() => EmailValidator), multi: true}));
    
/**
 * A Directive that adds the `email` validator to any controls marked with the
 * `email` attribute, via the {@link NG_VALIDATORS} binding.
 *
 * ### Example
 *
 * ```
 * <input type='email' ngControl="email">
 * ```
 */
@Directive({
  selector: '[type=email][ngControl],[type=email][ngFormControl],[type=email][ngModel]',
  providers: [EMAIL_VALIDATOR]
})
export class EmailValidator {
    emailRegExp = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/; 
    
    constructor () {}
    
    validate(control: Control): {[key: string]: any} { 
        return isBlank(control.value) || !this.emailRegExp.test(control.value) ?
               {"email": true} :
               null;
    }
}